package com.leyou.auth.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.entiry.ClientInfo;
import com.leyou.auth.mapper.ClientMapper;
import com.leyou.auth.service.ClientService;
import com.leyou.common.exception.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, ClientInfo> implements ClientService {


    @Value("${ly.jwt.key}")
    private String key;  //密匙

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 申请密匙
     * @param clientId  微服务id
     * @param secret  微服务密匙
     */

    @Override
    public String getSecretKey(String clientId, String secret) {
        // 1.查询client信息
        ClientInfo client = query().eq("client_id", clientId).one();
        if (client == null) {
            throw new LyException(401, "客户端的信息有误，" + clientId + "不存在！");
        }
        // 2.校验client的secret
        if (!passwordEncoder.matches(secret, client.getSecret())) {
            throw new LyException(401, "客户端的信息有误，secret不正确！");
        }
        // 3.返回秘钥
        return key;
    }



   /* @Autowired
    private ClientMapper clientMapper;
    @Override
    public String getSecretKey(String clientId, String secret) {
        //根据clientId查询clientInfo信息
        // 1.查询client信息
        ClientInfo clientInfo = clientMapper.getSecretKey(clientId);
//        ClientInfo clientInfo = query().eq("client_id", clientId).one();
        if (clientInfo == null) {
            throw new LyException(401, "客户端的信息有误，" + clientId + "不存在！");
        }
        //校验secret
        boolean result = passwordEncoder.matches(secret, clientInfo.getSecret());
        if (!result){
            throw new LyException(401, "客户端的信息有误，secret不正确！");
        }
        //将密匙密匙返回
        return key;
    }*/
}
